package com.icarbonx.dap.notification.job

import com.google.gson.Gson
import com.icarbonx.dap.notification.msgservice.rabbitmq.{ConnUtil, MQObject}
import com.icarbonx.dap.notification.util.{DateUtil, KafkaUtil, NoticeMsg, SparkUtil}
import com.icarbonx.dap.notification.vo._
import kafka.serializer.StringDecoder
import org.apache.log4j.{Level, Logger}
import org.apache.spark.SparkContext
import org.apache.spark.streaming.dstream.DStream
import org.apache.spark.streaming.kafka.KafkaUtils
import org.apache.spark.streaming.{Seconds, StreamingContext, _}

import scala.collection.mutable.ArrayBuffer

/**
 * Created by Lenovo on 2018/8/12.
 * 用户初始化信息中有用药方案，但一天未记录用药,这里需要访问 API
 */
object DrugStream {
  def main(args: Array[String]) {
    Logger.getLogger("org.apache.kafka").setLevel(Level.ERROR)
    Logger.getLogger("org.apache.zookeeper").setLevel(Level.ERROR)
    Logger.getLogger("org.apache.spark").setLevel(Level.ERROR)

    /**
     * brokers = "10.47.250.4:9092,10.47.250.7:9092,10.47.250.6:9092"
     * topicList = "abel_test"
     * mq:10.104.103.7 5672 guest icx@betaOn16 /
     * redis:10.104.103.7 6379 passxx#$#dslllfjshwerw123@ 3000 abel_test
     */
    println(args.mkString("\t"))
    val Array(brokers, sugarTopicList, topicList, drugTopic, mqHost, mqPort, mqUsername, mqPassword, mqVirtualHost,
    exchangeName, mqRouteKey, checkpointDir, duration, rddDuration, firstTime, secondTime, thirdTime, appName) = args
    //    val checkpointPath = "/data/streaming/checkpoint/drug_stream/"

    val conf = SparkUtil.getSparkConf(appName, Array(classOf[DrugRecord], classOf[DrugModel]))

    val sc = SparkContext.getOrCreate(conf)

    val updateFunc = (values: Seq[Long], state: Option[Long]) => {
      //保存状态
      val previousCount = state.getOrElse(0L)
      val newValue = if (values.isEmpty) 0L else values.max
      Some(math.max(newValue, previousCount))
    }

    val updateSugarFunc = (values: Seq[Long], state: Option[Long]) => {
      //保存状态
      val previousCount = state.getOrElse(0L)
      val result = if (previousCount == 0) values.min
      else if (values.isEmpty) previousCount
      else math.min(values.min, previousCount)
      Some(result)
    }

    def creatingFunc(): StreamingContext = {
      val ssc = new StreamingContext(sc, Seconds(duration.toInt))
      ssc.checkpoint(checkpointDir)
      val kafkaParams = KafkaUtil.getKafkaParam(brokers, appName)

      val mqConn = new MQObject(mqHost, mqPort.toInt, mqUsername, mqPassword, mqVirtualHost)

      val topics = topicList.split(",").toSet
      val drugModelTopics = drugTopic.split(",").toSet
      val sugarTopics = sugarTopicList.split(",").toSet

      val drugMessages = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](ssc,kafkaParams,topics )
      val drugModelMessages = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](ssc,kafkaParams,drugModelTopics )
      val sugarMessages = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder]( ssc, kafkaParams, sugarTopics )

      val sugarBatch: DStream[(String, Long)] =
        sugarMessages
          .filter(_._2.nonEmpty)
          .flatMap { msg =>
            try {
              println("___________ msg :" + msg._2)
              val gson = new Gson()
              val voList =
                gson.fromJson(msg._2, classOf[Array[BloodSugarRecord]])
              voList.map { vo =>
                (vo.personId.toString, vo.timestamp)
              }.toList
            } catch {
              case e: Exception =>
                println("____________" + e.getMessage)
                List(("", 0L))
            }
          }
          .filter(_._1.nonEmpty)
          .updateStateByKey(updateSugarFunc)

      sugarBatch.checkpoint(Duration(rddDuration.toInt * 1000))


      val drugBatch: DStream[(String, Long)] =
        drugMessages
          .filter(_._2.nonEmpty)
          .map { msg =>
            try {
              println("___________ msg :" + msg._2)
              val gson = new Gson()
              val vo = gson.fromJson(msg._2, classOf[DrugRecord])
              (vo.personId.toString, vo.actualDate)
            } catch {
              case e: Exception =>
                println("____________" + e.getMessage)
                ("", 0L)
            }
          }
          .filter(_._1.nonEmpty)
          .updateStateByKey(updateFunc)

      drugBatch.checkpoint(Duration(rddDuration.toInt * 1000))

      val drugModelBatch: DStream[(String, Long)] =
        drugModelMessages
          .filter(_._2.nonEmpty)
          .map { msg =>
            try {
              println("___________ msg :" + msg._2)
              val gson = new Gson()
              val vo = gson.fromJson(msg._2, classOf[DrugModel])
              (vo.personId.toString, vo.createTime)
            } catch {
              case e: Exception =>
                println("____________" + e.getMessage)
                ("", 0L)
            }
          }
          .filter(_._1.nonEmpty)
          .updateStateByKey(updateFunc)

      drugModelBatch.checkpoint(Duration(rddDuration.toInt * 1000))

      val sugarDrug = sugarBatch.join(drugModelBatch).leftOuterJoin(drugBatch)

      sugarDrug.foreachRDD(mess =>
        if (!mess.isEmpty()) {
          mess.foreachPartition(lines => {
            val nowactualDate = DateUtil.getTodayDateTime("yyyyMMddHHmmss")
            val mqMsg = ArrayBuffer[String]()
            val gson = new Gson()
            lines.foreach {
              case (pid, ((sugarTime, modelTime), drugTime)) => {
                println("____ pid :" + pid + ",,, drugTime:" + drugTime + ",,, sugarTime:" + sugarTime + ",,, modelTime:" + modelTime)
                val (firstStartTime, firstEndTime) =
                  DateUtil.calStartAndDuration(firstTime, duration)
                val (secondStartTime, secondEndTime) =
                  DateUtil.calStartAndDuration(secondTime, duration)
                val (thirdStartTime, thirdEndTime) =
                  DateUtil.calStartAndDuration(thirdTime, duration)
                // 每晚8点          @todo excel:5 用户初始化信息中有用药方案，但一天未记录用药

                if (
                  ((drugTime.isEmpty && nowactualDate - modelTime >= 20 * 60 * 60 * 1000 && nowactualDate - modelTime < 44 * 60 * 60 * 1000)
                    || (drugTime.isDefined && nowactualDate - drugTime.get >= 20 * 60 * 60 * 1000 && nowactualDate - drugTime.get < 44 * 60 * 60 * 1000))

                    && firstStartTime <= nowactualDate
                    && firstEndTime > nowactualDate
                ) {
                  val msg = new WarningMsg(
                    "glycemia",
                    pid.toLong,
                    NoticeMsg.miss_drug._1,
                    NoticeMsg.miss_drug._2,
                    NoticeMsg.miss_drug._3,
                    if (drugTime.isDefined) drugTime.get.toString else modelTime.toString,
                    NoticeMsg.miss_drug._5,
                    NoticeMsg.miss_drug._4,
                    NoticeMsg.miss_drug._6
                  )
                  mqMsg += gson.toJson(msg)
                }

                if (
                  ((drugTime.isEmpty && nowactualDate - modelTime >= 32 * 60 * 60 * 1000 && nowactualDate - modelTime < 56 * 60 * 60 * 1000)
                    || (drugTime.isDefined && nowactualDate - drugTime.get >= 32 * 60 * 60 * 1000 && nowactualDate - drugTime.get < 56 * 60 * 60 * 1000))

                    && secondStartTime <= nowactualDate
                    && secondEndTime > nowactualDate
                ) {
                  val msg = new WarningMsg(
                    "glycemia",
                    pid.toLong,
                    NoticeMsg.miss_drug._1,
                    NoticeMsg.miss_drug._2,
                    NoticeMsg.miss_drug._3,
                    if (drugTime.isDefined) drugTime.get.toString else modelTime.toString,
                    NoticeMsg.miss_drug._5,
                    NoticeMsg.miss_drug._4,
                    NoticeMsg.miss_drug._6
                  )
                  mqMsg += gson.toJson(msg)
                }


                if (
                  ((drugTime.isEmpty && nowactualDate - modelTime >= 36 * 60 * 60 * 1000 && nowactualDate - modelTime < 60 * 60 * 60 * 1000)
                    || (drugTime.isDefined && nowactualDate - drugTime.get >= 36 * 60 * 60 * 1000 && nowactualDate - drugTime.get < 60 * 60 * 60 * 1000))

                    && thirdStartTime <= nowactualDate
                    && thirdEndTime > nowactualDate
                ) {
                  val msg = new WarningMsg(
                    "glycemia",
                    pid.toLong,
                    NoticeMsg.miss_drug_12._1,
                    NoticeMsg.miss_drug_12._2,
                    NoticeMsg.miss_drug_12._3,
                    if (drugTime.isDefined) drugTime.get.toString else modelTime.toString,
                    NoticeMsg.miss_drug_12._5,
                    NoticeMsg.miss_drug_12._4,
                    NoticeMsg.miss_drug_12._6
                  )
                  mqMsg += gson.toJson(msg)
                }
              }
            }
            if (mqMsg.nonEmpty) {
              val mqChannel = mqConn.connect().createChannel()
              mqMsg.foreach { msg =>
                ConnUtil.sendMsg(mqChannel, exchangeName, mqRouteKey, msg)
              }
              mqChannel.close()
            }

          })

        })

      ssc
    }


    val ssc = StreamingContext.getOrCreate(checkpointDir, creatingFunc)

    ssc.start()
    ssc.awaitTermination()
  }
}